import Message from './sequelize/Message';
// import { LiveSession } from './sequelize'; // 暂不实现session逻辑
import { UserData, UserService } from './User';
import { RoomService } from './Room';
import { UserSnapshotService, UserSnapshotData } from './UserSnapshot';
import { LiveStreamMessage } from '../types/MessageTypes';
import { ensureUserId } from '../utils/anonymousUser';

export interface BaseMessage {
  id: string;
  method: string;
  user?: UserData;
  content?: string;
  room?: {
    audienceCount?: string;
    likeCount?: string;
    followCount?: string;
    totalUserCount?: string;
    status?: number;
  };
}

export class MessageService {
  private userService = new UserService();
  private roomService = new RoomService();
  private userSnapshotService = new UserSnapshotService();

  // 保存消息（使用用户快照）
  async saveMessage(messageData: LiveStreamMessage, roomId: string, sessionId: string) {
    try {
      // 检查消息是否包含用户信息
      const hasUser = 'user' in messageData && messageData.user;
      let userId: string | null = null;
      let userSnapshotId: string | null = null;

      // 如果有用户信息，创建或获取用户快照
      if (hasUser) {
        // 确保用户有ID（匿名用户会生成虚拟ID）
        userId = ensureUserId(messageData.user, roomId);

        const userSnapshotData: UserSnapshotData = {
          userId: userId, // 使用确保后的userId
          userName: messageData.user.name,
          userAvatar: messageData.user.avatar,
          payGrade: messageData.user.payGrade?.level ? parseInt(messageData.user.payGrade.level) : 0,
          fansLevel: messageData.user.fansClub?.data?.level || 0,
          fansClubName: messageData.user.fansClub?.data?.anchorId || null,       // 管理员权限字段

          isAdmin: messageData.user.isAdmin || false,
        };

        userSnapshotId = await this.userSnapshotService.ensureUserSnapshot(
          userId, // 使用确保后的userId
          userSnapshotData,
          messageData.user.gender,
          messageData.user.shortId,
          messageData.user.displayId
        );
      }

      // 保存消息（使用upsert避免重复插入）
      const [message, created] = await Message.upsert({
        id: messageData.id,
        roomId,
        userId: userId, // 使用确保后的userId（可能是真实ID或虚拟ID）
        sessionId,
        userSnapshotId,
        messageType: messageData.method,
        content: this.formatContent(messageData)
      });
      return message;
    } catch (error) {
      console.error('保存消息失败:', error);
      throw error;
    }
  }

  // 格式化消息内容
  private formatContent(messageData: LiveStreamMessage): string {
    switch (messageData.method) {
      case 'WebcastChatMessage':
        return messageData.content || '';
      case 'WebcastGiftMessage':
        return `送出${messageData.gift?.name} x${messageData.gift?.count || 1}`;
      case 'WebcastMemberMessage':
        return messageData.content || '进入直播间';
      case 'WebcastSocialMessage':
        return messageData.content || '关注了主播';
      case 'WebcastLikeMessage':
        return messageData.content || '为主播点赞了';
      case 'WebcastRoomUserSeqMessage':
        return `房间用户序列更新 - 观众数: ${messageData.room?.audienceCount}, 总用户数: ${messageData.room?.totalUserCount}`;
      case 'WebcastRoomStatsMessage':
        return `房间统计更新 - 观众数: ${messageData.room?.audienceCount}`;
      case 'WebcastRoomRankMessage':
        return '房间排行更新';
      default:
        return '';
    }
  }

  // 获取房间消息
  async getRoomMessages(roomId: string, limit = 100) {
    return await Message.findAll({
      where: { roomId },
      order: [['createdAt', 'DESC']],
      limit
    });
  }

  // 获取用户在房间的消息历史
  async getUserMessages(userId: string, roomId: string, limit = 50) {
    return await Message.findAll({
      where: {
        userId,
        roomId
      },
      order: [['createdAt', 'DESC']],
      limit
    });
  }


}